<template>
  <div>
    <!-- User界面 -->
    <div :class="{hidden: isHidden}">
      <div class="app-container">
        <!-- 搜索面板 -->
        <el-row>
          <search-panel
            v-model="groups"
            search
            :create="canCreate"
            user
            :item-name="$t('n')+$t('user')"
            :item-number="userList.length"
            @on-search="onSearch"
            @on-create="onCreate"
          />
        </el-row>
        <!-- 数据列表 -->
        <el-row>
          <el-table
            loading="listLoading"
            :data="pageList"
            :stripe="true"
            element-loading-text="Loading"
            :border="false"
            :header-cell-style="{color:'black'}"
            fit
            highlight-current-row
          >
            <el-table-column :label="$t('nickname')" align="center" min-width="16%">
              <template slot-scope="scope">
                <span>{{ scope.row.name }}</span>
              </template>
            </el-table-column>
            <el-table-column :label="$t('telephone')" align="center" min-width="20%">
              <template slot-scope="scope">
                <span>{{ scope.row.telephone }}</span>
              </template>
            </el-table-column>
            <el-table-column :label="$t('email')" align="center" min-width="29%">
              <template slot-scope="scope">
                <a :href="'mailto:' + scope.row.email">{{ scope.row.email }}</a>
              </template>
            </el-table-column>
            <el-table-column :label="$t('user') + $t('type')" align="center" min-width="16%">
              <template slot-scope="scope">
                <a v-if="getGroupName(scope.row.group_id) !== '无分组'" @click="toGroupListDetail(scope.row.group_id)">{{ getGroupName(scope.row.group_id) }}</a>
                <span v-else>{{ getGroupName(scope.row.group_id) }}</span>
              </template>
            </el-table-column>
            <!-- 第三列 操作 -->
            <el-table-column align="center" :label="$t('operation')" width="150px" fixed="right">
              <template slot-scope="scope" style="float: left;">
                <!-- 编辑权限（设置管理员类型） -->
                <span v-if="
                // 是管理员：可以修改开发者、普通用户的信息
                $store.getters.isAdmin() && $store.getters.isDeveloperGroup(scope.row.group_id) ||
                $store.getters.isAdmin() && $store.getters.isUserGroup(scope.row.group_id)
                "
                style="margin-right:3px" @click="toEdit(scope.row.id); editFormVisible = true">
                  <a>{{ $t('edit') }}</a>
                </span>

                <!-- 删除权限 -->
                <span v-if="
                // 是管理员：可以删除开发者、用户
                $store.getters.isAdmin() && $store.getters.isDeveloperGroup(scope.row.group_id) ||
                $store.getters.isAdmin() && $store.getters.isUserGroup(scope.row.group_id)
                "
                @click="onDelete(scope.row.id)">
                  <a>{{ $t('delete') }}</a>
                </span><br>

                <!-- 重置密码 -->
                <span v-if="
                // 是管理员：可以重置开发者、用户的密码
                $store.getters.isAdmin() && $store.getters.isDeveloperGroup(scope.row.group_id) ||
                $store.getters.isAdmin() && $store.getters.isUserGroup(scope.row.group_id)
                "
                style="margin-right:3px" @click="resetPassword(scope.row.id)">
                  <a>{{ $t('reset') }}{{ $t('password') }}</a>
                </span>
              </template>
            </el-table-column>
          </el-table>

          <!-- 页数-->
          <el-row>
            <el-pagination
              align="center"
              :current-page="currentPage"
              :page-size="pageSize"
              :page-count="pageNum"
              @current-change="handlePageChange"
            />
          </el-row>
        </el-row>

        <div :class="{hidden: !isHidden}">
          <router-view />
        </div>

        <!-- 更新用户浮窗 -->
        <!-- <el-dialog :title="$t('edit')" :visible.sync="editFormVisible">
          <el-form ref="editForm" :model="editForm" :rules="rules">
            <el-form-item :label="$t('nickname')" label-width="120px" prop="name">
              <el-input v-model="editForm.name" autocomplete="off" />
            </el-form-item>
            <el-form-item :label="$t('telephone')" label-width="120px" prop="telephone">
              <el-input v-model="editForm.telephone" autocomplete="off" />
            </el-form-item>
            <el-form-item :label="$t('email')" label-width="120px" prop="email">
              <el-input v-model="editForm.email" autocomplete="off" />
            </el-form-item>
            <el-form-item :label="$t('user') + $t('group')" label-width="120px" prop="groupId">
              <el-select v-model="editForm.groupId">
                <el-option v-for="(g, index) in filteredGroupList" :key="index" :label="g.name" :value="g.id"/>
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="editFormVisible = false">{{ $t('cancel') }}</el-button>
            <el-button type="primary" @click="onEdit">{{ $t('confirm') }}</el-button>
          </div>
        </el-dialog> -->
      </div>
    </div>

    <div :class="{hidden: !isHidden}">
      <router-view />
    </div>
  </div>
</template>

<script>
import { getUserList, getGroupList, deleteUser, resetPassword, searchUser} from '@/api/user'
import { deleteByCreatorId, deleteUserPublished, deleteUserStars} from '@/api/app'
import { deleteUserProfile } from '@/api/profile'
import SearchPanel from '@/components/SearchPanel/index.vue'

function newForm() {
  return {
    id: 0,
    name: '',
    telephone: '',
    email: '',
    groupId: 1
  }
}

function checkPhone(rule, value, callback) {
  const reg = /^\d{11}$/
  if (!reg.test(value)) {
    callback(new Error(this.$t('user_phone_rule')))
  } else {
    callback()
  }
}

export default {
  components: {
    SearchPanel
  },
  data() {
    return {
      // 查询
      searchForm: {
        key: ''
      },
      list: [],
      userList: [],
      groupList: [],
      form: newForm(),
      editForm: {},
      listLoading: true,
      createFormVisible: false,
      editFormVisible: false,
      resetDialogVisible: false,
      resetPasswordInput: '',
      resetID: 0,
      setPasswdForm: {
        oldPwd: '',
        pwd: '',
        confirmPassword: ''
      },
      pageList: [],
      currentPage: 1,
      pageSize: 15,
      pageNum: 0,
      status: ["管理员", "开发者", "用户"],
      rules: {
        name: [
          { required: true, message: '请输入用户名称', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        telephone: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { min: 11, max: 11, message: this.$t('user_phone_rule'), trigger: 'blur' },
          { type: 'number', validator: checkPhone, message: '请填写正确手机号', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        groupId: [
          { required: true, message: '请选择用户组', trigger: 'blur' }
        ]
      },
      modifyPasswordRules: {
        oldPwd: [
          { required: true, message: '请输入旧密码', trigger: 'blur' }
        ],
        pwd: [
          { required: true, message: '请输入新密码', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value === this.setPasswdForm.pwd) {
                callback()
              } else {
                callback(new Error('两次输入密码不一致'))
              }
            },
            trigger: 'blur'
          }
        ]
      },
      hidden: true,

      // 用于三极路由
      isHidden: false
    }
  },
  created() {
    // 添加权限校验逻辑
    if (!this.$store.getters.isAdmin()) {
      this.$message({
        type: 'error',
        message: '您没有权限访问此页面'
      });
      this.$router.push('/'); 
      return;
    }
    if (this.$route.path !== '/configuration/user') this.isHidden = true
    this.getData()
    this.freshList(1)
  },
  computed: {
    // 计算属性过滤掉 id=1 的用户组（管理员）
    filteredGroupList() {
      return this.groupList.filter(g => g.id !== 1);
    },
    canCreate() {
      return this.$store.getters.isAdmin();
    },
  },
  methods: {
    // 更新列表
    freshList(nowPage) {
      const params = {
        'page': nowPage,
        'pagesize': this.pageSize,
        searchKey: this.searchForm.key
      }
    },
    handlePageChange(nowPage) {
      this.pageNum = parseInt((this.userList.length - 1) / this.pageSize) + 1
      this.pageList = this.userList.slice((nowPage - 1) * this.pageSize, nowPage * this.pageSize)
      this.currentPage = nowPage
    },
    getData() {
      this.listLoading = true;
      getGroupList().then(response => {
        this.groupList = response.data;
        this.form.groupId = this.groupList[0].id;
      });
      getUserList().then(response => {
        this.userList = response.data.sort((a, b) => a.group_id - b.group_id); // 按照group_id升序排序
        this.handlePageChange(1); 
        this.listLoading = false;
      });
    },
    getGroupName(group_id) {
      for (var i = 0; i < this.groupList.length; i++) {
        if (group_id === this.groupList[i].id) {
          return this.groupList[i].name
        }
      }
    },
    // 支持针对用户的姓名、手机、邮箱、用户类型（通过下拉按钮选择（管理员/用户））等字段的模糊搜索
    onSearch(key, status, namespace, chart, label) {
      let searchValue = {
        'search': key,
        'status': status
      }
      searchValue = JSON.stringify(searchValue)
      searchUser(searchValue).then(response => {
        this.$message({
          message: this.$t('查询成功'),
          type: 'success'
        })
        const data = response
        this.totalNum = data ? data.length : 0
        data.sort((a, b) => a.group_id - b.group_id)
        this.list = data
        this.pageList = data.slice(0, this.pageSize)
        this.currentPage = 1
        this.pageNum = parseInt((this.totalNum - 1) / this.pageSize) + 1
        this.freshList(1)
      }).catch(error => {
        console.log(error)
        this.$message({
          message: this.$t('查询失败'),
          type: 'error'
        })
      })
    },
    onCreate() {
      this.$router.push({ path: '/configuration/user/create' })
    },
    onCancle() {
      this.form = newForm()
      this.createFormVisible = false
    },
    loadUserInfo(user) {
      this.editForm = {
        id: user.id,
        name: user.name,
        telephone: user.telephone,
        email: user.email,
        groupId: user.group_id
      }
    },
    toEdit(id){
      this.$router.push({ path: '/configuration/user/edit/' + id })
    },
    onDelete(id) {
      this.$confirm('请注意删除用户将会同时删除此用户创建的全部应用，且无法恢复！是否要继续删除此用户？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false
      }).then(() => {
        // 先删除此用户创建的全部应用
        deleteUserProfile(id).then(() => {
          // this.$message({
          //   type: 'success',
          //   message: '删除成功'
          // })
          this.getData(1)
        })
        deleteUserPublished(id).then(() => {
          // this.$message({
          //   type: 'success',
          //   message: '删除成功'
          // })
          this.getData(1)
        })
        deleteUserStars(id).then(() => {
          // this.$message({
          //   type: 'success',
          //   message: '删除成功'
          // })
          this.getData(1)
        })
        deleteByCreatorId(id).then(() => {
          // this.$message({
          //   type: 'success',
          //   message: '删除成功'
          // })
          this.getData(1)
        })
        // 再删除此用户
        deleteUser(id).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功'
          })
          this.getData(1)
        })
      }).catch(() => { })
    },
    resetPassword(id) {
      this.$confirm('此操作将重置该用户密码, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false
      }).then(() => {
        resetPassword(id).then(() => {
          this.$message({
            type: 'success',
            message: '重置成功'
          })
          this.getData(1)
        })
      })
    },
    resetPasswordForm() {
      this.setPasswdForm.oldPwd = '';
      this.setPasswdForm.pwd = '';
      this.setPasswdForm.confirmPassword = '';
    }
  }
}
</script>

<style>
.app-container{
  padding: 20px;
}
.font-blue {
  color: #66b1ff
}
.hidden{
  display: none;
}

.create-container {
  margin-top: 20px;
  background-color: white;
  padding-top: 20px;
}
.descriptions {
  margin-top: 15px
}

.rule-form {
  width: 900px
}

.el-upload {
  width: 100%;
}

.el-upload .el-upload-dragger {
  width: 100%;
}

.el-row {
  margin-bottom: 2px; 
}


.el-form-item {
  margin-bottom: 10px; 
}

.el-form-item input[type="checkbox"] {
  margin-right: 5px; 
  vertical-align: middle; 
}

.el-form-item label {
  display: inline-block; 
  vertical-align: middle; 
  color: gray; 
  font-weight: normal;
}
.el-table__row {
  cursor: move; /* 添加鼠标指针样式，表示可以拖拽 */
}
.task-container {
  display: flex;
  align-items: center;
}

.task-number {
  margin-right: 18px;
  margin-left: 10px;
}

.header-buttons, .cell-buttons {
  display: flex;
  justify-content: flex-end; /* 使按钮右对齐 */
  margin-right: 10px;
  /*align-items: center; !* 垂直居中对齐 *!*/
}


.el-table .el-table__body-wrapper {
  overflow-x: hidden; /* 隐藏横向滚动条 */
}
.el-table {
  table-layout: fixed; /* 固定表格布局，防止内容溢出 */
}

.custom-table {
  border: 1px  solid #dcdfe6; /* 边框颜色 */
  border-radius: 5px;
  /*border-collapse: collapse; !* 边框合并 *!*/
}
</style>
